package com.banmao.CarlCamp.Day04;

/**
 * https://leetcode.cn/problems/linked-list-cycle-ii/
 */
public class LC142 {

    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null || head.next.next == null) {
            return null;
        }
        // 判断链表是否有环，我记得需要使用快慢指针
        // 快指针一次走两步，慢指针一次走一步，如果相遇，则有环
        ListNode fast = head.next.next, slow = head.next;
        ListNode meetNode = null;
        while (slow != null) {
            if (fast == slow) {
                meetNode = fast;
                break;
            }
            if (fast.next == null || fast.next.next == null) {
                break;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        if (meetNode == null) {
            return null;
        }
        // 从相遇节点开始，一个指针从 meetNode，另一个从 head，同步遍历，相遇的节点就是环的入口
        slow = head;
        fast = meetNode;
        while (slow != fast) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }

    class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }

}
